<template>
  <div class="fromStyle">
    <el-card style="max-width: 600px">
      <h2>用户登录</h2>
      <el-form :model="formData" ref="loginForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="学号" prop="studentId" style="font-size: 18px; color: #333">
          <el-input
            v-model="formData.studentId"
            style="width: 100%"
            placeholder="请使用学号注册登录"
            autocomplete="new-password"
          />
        </el-form-item>

        <el-form-item label="密码" prop="websitePw" style="font-size: 18px; color: #333">
          <el-input
            v-model="formData.websitePw"
            style="width: 100%"
            placeholder="请输入网站密码（非MySeig系统密码）"
            show-password
            autocomplete="new-password"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: center; align-items: center; margin-top: 24px; gap: 12px">
        <!-- <el-button @click="handleRegister" link> 没有账号？来注册 </el-button> -->
        <el-button type="info" @click="handleRegister" round :disabled="isMobile" v-if="!isMobile">注册</el-button>
        <!-- 账号输入气泡弹窗 -->
        <el-popover
          v-model:visible="showPopover"
          placement="bottom"
          title="请输入账号"
          :width="200"
          trigger="manual"
          v-if="!isMobile"
        >
          <el-input v-model="formData.studentId" placeholder="请输入您的账号" />
          <div style="margin-top: 10px; text-align: right">
            <el-button size="small" @click="showPopover = false">取消</el-button>
            <el-button size="small" type="primary" @click="handleConfirm">确认</el-button>
          </div>
          <template #reference>
            <el-button type="warning" @click="showPopover = true" round :disabled="isMobile" v-if="!isMobile"
              >忘记密码</el-button
            >
          </template>
        </el-popover>
        <el-button type="primary" @click="handleManual" round>指南</el-button>
        <el-button type="success" @click="handleLogin" round :disabled="isMobile">登录</el-button>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, onMounted, ref } from "vue";
  import router from "../router";
  import api from "../axios/api";
  import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
  interface FormData {
    studentId: string;
    websitePw: string;
  }

  const formData = reactive<FormData>({
    studentId: "",
    websitePw: ""
  });
  const isMobile = ref(false);
  // 添加设备检测函数
  const checkDevice = () => {
    isMobile.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    if (isMobile.value) {
      ElMessage.error({
        message: "请使用PC端访问本平台",
        duration: 0,
        showClose: false
      });
      router.push("/unsupported");
    }
  };

  onMounted(() => {
    // 如果是从注册页面跳转过来的,获取注册时保存的账号密码
    const studentId = localStorage.getItem("studentId");
    const websitePw = localStorage.getItem("websitePw");
    checkDevice();
    if (studentId && websitePw) {
      formData.studentId = studentId;
      formData.websitePw = websitePw;
      // 清除localStorage中的密码
      localStorage.removeItem("websitePw");
    }
  });

  const handleLogin = async () => {
    if (!formData.studentId || !formData.websitePw) {
      ElMessage.warning("请输入账号和密码");
      return;
    }
    const loading = ElLoading.service({
      lock: true,
      text: "登录中...",
      background: "rgba(0, 0, 0, 0.7)"
    });

    try {
      const res = await api.userLogin(formData.studentId, formData.websitePw);
      if (res.status === 200) {
        // 清除localStorage中的数据
        localStorage.clear();
        localStorage.setItem("studentId", formData.studentId);
        localStorage.setItem("token", res.data.access_token);
        localStorage.setItem("userId", res.data.user_id);
        // 请求全部课程
        const course_res = await api.getAllCourse();
        if (course_res.status === 200) {
          console.log(course_res.data);
          localStorage.setItem("course_data", JSON.stringify(course_res.data));
          localStorage.setItem("role", res.data.role);
        } else {
          ElMessage.error(course_res.data.message);
        }
        // 获取识别码
        const recognition_code_res = await api.getRecognitionCode();
        console.log(recognition_code_res);
        if (recognition_code_res.status === 200) {
          localStorage.setItem("recognition_code", recognition_code_res.data.recognitionCode);
        }
        // 获取全部课表
        const all_schedules_res = await api.getAllSchedules();
        console.log("全部课表");
        console.log(all_schedules_res);
        if (all_schedules_res.status === 200) {
          const tableData = all_schedules_res.data.map((item: any) => {
            if (item.schedules) {
              return item;
            }
          });
          // 排序
          tableData.sort(
            (a: any, b: any) => a.year_term.year - b.year_term.year || a.year_term.semester - b.year_term.semester
          );
          localStorage.setItem("tableData", JSON.stringify(tableData));
          if (tableData.length > 0) {
            const userInfo = tableData[0].personal_info;
            localStorage.setItem("userInfo", JSON.stringify(userInfo));
          }
        }

        ElMessage({
          message: "登录成功!",
          type: "success",
          duration: 1000
        });
        router.push({
          path: "/home"
        });
      } else {
        ElMessage.error(res.data.message);
      }
    } catch (error: any) {
      // ElMessage.error(error.toString());
      console.error(error);
    } finally {
      loading.close();
    }
  };
  const handleRegister = () => {
    // router.push("/register");
    ElMessage.warning("不再支持网页端注册，请在小程序「课不要」中使用MySeig注册");
  };
  const handleManual = () => {
    window.open(import.meta.env.VITE_API_BASE_URL + "/manual_html/index.html", "_blank");
  };

  const showPopover = ref(false);

  const handleConfirm = async () => {
    if (!formData.studentId) {
      ElMessage.warning("请输入账号");
      return;
    }

    try {
      // 二次确认弹窗
      await ElMessageBox.confirm(
        `确定要重置 ${formData.studentId} 的密码吗？新密码将通过邮箱发送至账号注册邮箱`,
        "确认重置密码",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      // 调用重置密码接口
      const res = await api.resetPassword(formData.studentId);
      if (res.status === 200) {
        ElMessage.success(res.data.message);
      } else {
        ElMessage.error(res.data.message);
      }

      // 重置状态
      // formData.studentId = '';
      showPopover.value = false;
    } catch (error) {
      // 用户点击取消或请求失败
      if (error !== "cancel") {
        ElMessage.error("密码重置失败，请稍后重试");
      }
    }
  };
</script>
<style lang="less" scoped>
  .fromStyle {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url("../assets/5.jpg");
    background-size: cover;
    background-position: center;
    h2 {
      text-align: center;
      margin-bottom: 20px;
    }
  }
  .fromStyle::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: inherit;
    background-size: inherit;
    background-position: inherit;
    filter: blur(4px);
    z-index: -1;
  }
</style>
